﻿using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.SystemModule;
using DevExpress.Persistent.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XafListViewDefaultNoLoadData.Module.BusinessObjects;

namespace XafListViewDefaultNoLoadData.Module.Controllers {
  public class TStudentVc : ObjectViewController<ListView, TStudentBo> {
    public TStudentVc() : base() {
      // 自定义功能按钮，实现自定义查询功能
      var bAction = new ParametrizedAction(this, "学生查询", PredefinedCategory.View, typeof(string)) { ImageName = "Action_Search" };
      bAction.NullValuePrompt = "输入“张三”查询";
      bAction.Execute += BAction_Execute; ;
    }

    private void BAction_Execute(object sender, ParametrizedActionExecuteEventArgs e) {
      View.CollectionSource.Criteria.Clear();
      var bStudsQuery = View.ObjectSpace.GetObjectsQuery<TStudentBo>(true);
      var bParamValue = e.ParameterCurrentValue as string;

      if (string.IsNullOrWhiteSpace(bParamValue)) {
        View.CollectionSource.Criteria["自定义搜索"] =
          //CriteriaOperator.Parse("Name = '123'");
          CriteriaOperator.FromLambda<TStudentBo>(_ => false);
      }
      else {
        View.CollectionSource.Criteria["自定义搜索"] = CriteriaOperator.FromLambda<TStudentBo>(s => s.Name.Contains(bParamValue));
      }
    }

    protected override void OnActivated() {
      base.OnActivated();

      // 参考：https://blog.csdn.net/hacky_way/article/details/7753890
      // 参考：https://xafmarin.com/xaf-loading-empty-listview-until-the-user-does-a-search/
      // 参考：https://supportcenter.devexpress.com/ticket/details/as13324/how-to-search-or-filter-listview-records-via-several-required-properties
      // 默认列表不加载数据
      View.CollectionSource.Criteria["自定义搜索"] = CriteriaOperator.FromLambda<TStudentBo>(_ => false);
      var bFilterController = Frame.GetController<FilterController>();
      if (bFilterController != null) {
        // 参考：隐藏或禁用按钮
        // https://docs.devexpress.com/eXpressAppFramework/112728/ui-construction/controllers-and-actions/actions/how-to-deactivate-hide-an-action-in-code
        bFilterController.FullTextFilterAction.Active.SetItemValue("Hidden", false);
      }
    }

    //private void FullTextFilterAction_Executed(object sender, DevExpress.ExpressApp.Actions.ActionBaseEventArgs e) {
    //  throw new NotImplementedException();
    //}

    protected override void OnDeactivated() {
      // Unsubscribe from previously subscribed events and release other references and resources.
      base.OnDeactivated();
    }
    protected override void OnViewControlsCreated() {
      base.OnViewControlsCreated();
      // Access and customize the target View control.
    }
  }
}
